﻿using AutoUpdateTool.Properties;
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace AutoUpdateTool
{
    public partial class SettingForm : Form
    {
        public SettingForm()
        {
            InitializeComponent();
            this.StartPosition = FormStartPosition.CenterScreen;
        }

        private void SettingForm_Load(object sender, EventArgs e)
        {
            this.Invoke(new MAction(() => {
                if (Common.InitLocked)
                {
                    this.tx_configurl.Text = Common.ConfigUrl;
                    this.tx_approotpath.Text = Common.FilesRootPath;
                    this.tx_applaunchexe.Text = Common.AppLaunchExe;
                    this.cb_formtype.Checked = Common.UseFormLite;
                    this.cb_autoupdate.Checked = Common.AutoUpdate;
                    this.cb_apprestart.Checked = Common.AppRestart;
                }
            }));
        }

        private void btn_save_Click(object sender, EventArgs e)
        {
            this.Invoke(new MAction(() => {
                if (string.IsNullOrEmpty(this.tx_configurl.Text))
                {
                    MessageBox.Show("配置文件地址不能为空");
                    return;
                }
                Common.ConfigUrl = Common.FormatManifestUrl(this.tx_configurl.Text);
                Common.FilesRootPath = Common.TrailingPath(this.tx_approotpath.Text);
                Common.AppLaunchExe = Common.TrailingFilePath(this.tx_applaunchexe.Text);
                Common.UseFormLite = this.cb_formtype.Checked;
                Common.AutoUpdate = this.cb_autoupdate.Checked;
                Common.AppRestart = this.cb_apprestart.Checked;
                Common.InitLocked = true;

                this.Dispose();
            }));
            
        }
        
        #region 设置窗体无边框可拖动
        [DllImport("user32.dll")]
        public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wparam, int lparam);
        protected override void OnMouseDown(MouseEventArgs e)
        {
            base.OnMouseDown(e);
            if (e.Button == MouseButtons.Left)//按下的是鼠标左键            
            {
                Capture = false;//释放鼠标使能够手动操作                
                SendMessage(Handle, 0x00A1, 2, 0);//拖动窗体            
            }
        }

        [DllImport("User32.DLL")]
        public static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);
        [DllImport("User32.DLL")]
        public static extern bool ReleaseCapture();
        public const uint WM_SYSCOMMAND = 0x0112;
        public const int SC_MOVE = 61456;
        public const int HTCAPTION = 2;

        private void Control_MouseDown(object sender, MouseEventArgs e)
        {
            ReleaseCapture();
            SendMessage(Handle, WM_SYSCOMMAND, SC_MOVE | HTCAPTION, 0);
        }
        #endregion

    }
}
